/* 
Program to get link to SOEP by merging linkage table.
Leaves merge in dataset. 
Important note: as long as there are duplicates in the key merges using 
different merge variables need not be equivalent. 
*/

* Get Linked Individuals
cap program drop getlinkSN
program define getlinkSN
    
    syntax, mergevar(varname) [table(string)]

    preserve    
    if "`table'" == "" use $orig_adiab/$linkage_table, clear
    // For test-purposes use FDZ/Josua Key which does only have pid
    if "`table'" == "fdz" use $orig_adiab/SOEP-ADIAB_7519_v1_key, clear
    * When using the standard key in Josua prs_id is not in the table
    cap clonevar persnr = pid
    cap clonevar persnr = prs_id

    cap clonevar prs_id = pid
    cap clonevar prs_id = persnr
    
    * Drop missings
    drop if missing(prs_id)
    drop if missing(pid)

    * Clean duplicates
    bys pid (prs_id): gen select = _n == 1
    keep if select == 1
    drop select
    
    bys prs_id (pid): gen select = _n == 1
    keep if select == 1
    drop select

    isid persnr
    isid prs_id
    isid pid

    tempfile isid_link
    save `isid_link'
    restore

    merge m:1 `mergevar' using `isid_link', keepusing(`mergevar' pid)

end
